package com.db.yupao.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.db.yupao.common.ResultUtils;
import com.db.yupao.mapper.UserMapper;
import com.db.yupao.model.pojo.User;
import com.db.yupao.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: yupao-back
 * @ClassName: PreCacheJob
 * @Author: LYP
 * @Version: 1.0.0
 * @CreateTime:2025/8/15 11:01
 * @Description: 缓存预热
 */

@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    // 重点用户
    private List<Long> mainUserList = Arrays.asList(1L);

    @Scheduled(cron = "0 59 23 * * ? ")
    synchronized public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");
        try {
            // 只有一个线程能获取到锁
            if (lock.tryLock(0,30000, TimeUnit.MILLISECONDS)) {
                for (Long userid : mainUserList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    String key = String.format("yupao:user:recommend:%s", userid);
                    ValueOperations<String, Object> ValueOperations = redisTemplate.opsForValue();
                    Page<User>  userList = userService.page(new Page<>(1, 20), queryWrapper);

                    try {
                        ValueOperations.set(key, userList, 60 * 60 * 10, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.error("redis error :{}", e);
                        throw new RuntimeException(e);
                    }
                }
            }

        } catch (InterruptedException e) {
            log.error("添加分布式锁时报错了:{}",e);
        }finally {
            // 只能释放掉 自己添加的锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }


        log.info("doCacheRecommendUser");
    }
}
